package co.fitstart.tencent.web.controller.token;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.demo2do.core.support.Result;
import com.demo2do.core.utils.JsonUtils;
import com.demo2do.core.wechat.handler.WechatHandler;
import com.demo2do.core.wechat.support.AppType;

/**
 *
 * @author downpour
 * @author lute
 */
@Controller
@RequestMapping("")
public class AccessTokenController {

    private static final Logger logger = LoggerFactory.getLogger(AccessTokenController.class);

    @Autowired
    private WechatHandler wechatHandler;

    /**
     * Retrieve global access token
     *
     * @param appType  the application type of WeChat account for retrieving access token
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/wechat-access-token", method = RequestMethod.GET)
    public String getAccessToken(@RequestParam(value = "appType", required = false, defaultValue = "OFFICIAL") AppType appType) {
        Result result = new Result();
        try {
            String accessToken = wechatHandler.requestAccessToken(appType);
            result.success()
                  .data("access_token", accessToken);
        } catch (Exception e) {
            logger.error("AccessTokenController#getAccessToken - Getting access token for app type [{}] encounters exception: {}", appType, e);
            result.fail().message(e.getMessage());
        }
        return JsonUtils.toJsonString(result);
    }

    /**
     * Retrieve JS ticket for requesting
     *
     * @param appType
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/wechat-js-ticket", method = RequestMethod.GET)
    public String getJsTicket(@RequestParam(value = "appType", required = false, defaultValue = "OFFICIAL") AppType appType){
        Result result = new Result();
        try {
            String jsTicket = wechatHandler.requestJsTicket(appType);
            result.success()
                  .data("js_ticket", jsTicket);
        } catch (Exception e) {
            logger.error("AccessTokenController#getJsTicket - Getting JS ticket for app type [{}] encounters exception: {}", appType, e);
            result.fail().message(e.getMessage());
        }
        return JsonUtils.toJsonString(result);
    }

}
